import axios from 'axios'
import router from '@/router/index'
import store from '@/store/index'

axios.defaults.headers.common['access_token'] = window.localStorage.getItem('access_token')
axios.defaults.headers.post['Content-Type'] = 'application/json;charset=UTF-8'
// axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'
// axios.defaults.headers.get['Content-Type'] = 'application/x-www-form-urlencoded'
axios.interceptors.request.use(config => {
  if (window.localStorage.getItem('access_token') !== '') {
    store.commit('set_token', window.localStorage.getItem('access_token'))
    config.headers.access_token = `${store.state.token}`
  }
  return config
}, function (error) {
  // 对请求错误做些什么
  return Promise.reject(error)
})

axios.interceptors.response.use(response => {
  if (!response.data.result && response.data.code === '403') {
    window.localStorage.setItem('access_token', '')
    router.push({path: '/login'})
    return response
  } else {
    return response
  }
}, function (error) {
  return Promise.reject(error)
})
export default axios
